<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Agent管理</span>
          <el-button type="primary" @click="handleAdd">新增Agent</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="is_hot" label="热门" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_hot ? 'success' : 'info'">
              {{ row.is_hot ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'">
              {{ row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        @current-change="loadData"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入Agent名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入Agent描述" />
        </el-form-item>
        <el-form-item label="模型">
          <el-select v-model="form.model_id" placeholder="请选择模型">
            <el-option 
              v-for="model in models" 
              :key="model.id" 
              :label="model.name" 
              :value="model.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="form.category_id" placeholder="请选择分类">
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-divider content-position="left">参数配置</el-divider>
        <el-form-item label="Temperature">
          <el-input-number 
            v-model="paramsForm.temperature" 
            :min="0" 
            :max="2" 
            :step="0.1" 
            :precision="1"
            placeholder="0-2，数值越大越有创造性"
          />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            控制创造性，0=保守，2=创造
          </span>
        </el-form-item>
        <el-form-item label="Max Tokens">
          <el-input-number 
            v-model="paramsForm.max_tokens" 
            :min="1" 
            :max="32000" 
            :step="100"
            placeholder="最大输出长度"
          />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            最大输出token数量
          </span>
        </el-form-item>
        <el-form-item label="Top P">
          <el-input-number 
            v-model="paramsForm.top_p" 
            :min="0" 
            :max="1" 
            :step="0.1" 
            :precision="2"
            placeholder="0-1"
          />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            核采样参数
          </span>
        </el-form-item>
        <el-form-item label="JSON格式预览">
          <el-input 
            v-model="paramsJson" 
            type="textarea" 
            :rows="3" 
            readonly
            placeholder="参数的JSON格式"
          />
        </el-form-item>
        
        <el-divider content-position="left">角色设定</el-divider>
        <el-form-item label="角色名称">
          <el-input v-model="roleForm.role_name" placeholder="请输入角色名称，如：专业的AI助手" />
        </el-form-item>
        <el-form-item label="角色背景">
          <el-input 
            v-model="roleForm.role_background" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色背景，如：你是一个拥有丰富经验的AI技术专家..."
          />
        </el-form-item>
        <el-form-item label="角色性格">
          <el-input 
            v-model="roleForm.personality" 
            type="textarea" 
            :rows="2"
            placeholder="请输入角色性格，如：友好、专业、耐心、乐于助人"
          />
        </el-form-item>
        <el-form-item label="JSON格式预览">
          <el-input 
            v-model="roleJson" 
            type="textarea" 
            :rows="3" 
            readonly
            placeholder="角色设定的JSON格式"
          />
        </el-form-item>
        
        <el-divider content-position="left">RAG 知识库配置（可选）</el-divider>
        <el-form-item label="创建知识库">
          <el-input v-model="ragForm.kb_name" placeholder="输入知识库名称" style="margin-bottom: 10px;" />
          <el-input v-model="ragForm.kb_description" type="textarea" :rows="2" placeholder="知识库描述（可选）" style="margin-bottom: 10px;" />
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :multiple="true"
            :file-list="ragForm.fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept=".txt,.md,.pdf,.docx,.doc"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 txt、md、pdf、docx 格式，可多选
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="或选择已有知识库">
          <el-select v-model="form.rag_kb_id" placeholder="选择知识库（可选）" clearable @change="handleKbChange">
            <el-option 
              v-for="kb in knowledgeBases" 
              :key="kb.id" 
              :label="`${kb.name} (${kb.completed_docs}/${kb.total_docs})`" 
              :value="kb.id" 
            />
          </el-select>
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            如果创建新知识库，此选项将被忽略
          </span>
        </el-form-item>
        
        <el-divider />
        <el-form-item label="热门工具">
          <el-switch v-model="form.is_hot" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { getAgents, createAgent, updateAgent, deleteAgent, getModels } from '@/api/admin'
import request from '@/api/request'

const loading = ref(false)
const tableData = ref([])
const models = ref([])
const categories = ref([])
const knowledgeBases = ref([])
const uploadRef = ref(null)
const pagination = reactive({
  page: 1,
  pageSize: 15,
  total: 0
})

const dialogVisible = ref(false)
const dialogTitle = ref('新增Agent')
const submitting = ref(false)
const form = reactive({
  id: null,
  name: '',
  description: '',
  model_id: 1,
  category_id: null,
  rag_kb_id: null,
  is_hot: false,
  enabled: true
})

// 参数配置表单
const paramsForm = reactive({
  temperature: 0.7,
  max_tokens: 2000,
  top_p: 0.9
})

// 角色设定表单
const roleForm = reactive({
  role_name: '',
  role_background: '',
  personality: ''
})

// RAG 知识库表单
const ragForm = reactive({
  kb_name: '',
  kb_description: '',
  fileList: []
})

// 参数JSON预览
const paramsJson = computed(() => {
  const params = {}
  if (paramsForm.temperature !== null && paramsForm.temperature !== undefined) {
    params.temperature = paramsForm.temperature
  }
  if (paramsForm.max_tokens !== null && paramsForm.max_tokens !== undefined) {
    params.max_tokens = paramsForm.max_tokens
  }
  if (paramsForm.top_p !== null && paramsForm.top_p !== undefined) {
    params.top_p = paramsForm.top_p
  }
  return JSON.stringify(params, null, 2)
})

// 角色JSON预览
const roleJson = computed(() => {
  const role = {}
  if (roleForm.role_name) role.role_name = roleForm.role_name
  if (roleForm.role_background) role.role_background = roleForm.role_background
  if (roleForm.personality) role.personality = roleForm.personality
  return JSON.stringify(role, null, 2)
})

const loadData = async () => {
  try {
    loading.value = true
    const res = await getAgents({
      page: pagination.page,
      page_size: pagination.pageSize
    })
    tableData.value = res.data.items
    pagination.total = res.data.total
  } catch (error) {
    console.error(error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadModels = async () => {
  try {
    const res = await getModels({ page: 1, page_size: 100 })
    models.value = res.data.items
  } catch (error) {
    console.error(error)
    ElMessage.error('加载模型列表失败')
  }
}

const loadCategories = async () => {
  try {
    const res = await request.get('/categories')
    categories.value = res.data || []
  } catch (error) {
    console.error(error)
    ElMessage.error('加载分类列表失败')
  }
}

const loadKnowledgeBases = async () => {
  try {
    const res = await request.get('/knowledge/knowledge-bases')
    knowledgeBases.value = res.data || []
  } catch (error) {
    console.error(error)
    ElMessage.error('加载知识库列表失败')
  }
}

const handleFileChange = (file, fileList) => {
  ragForm.fileList = fileList
}

const handleFileRemove = (file, fileList) => {
  ragForm.fileList = fileList
}

const handleKbChange = (value) => {
  // 选择已有知识库时，清空新建知识库的表单
  if (value) {
    ragForm.kb_name = ''
    ragForm.kb_description = ''
    ragForm.fileList = []
  }
}

const resetForms = () => {
  Object.assign(form, {
    id: null,
    name: '',
    description: '',
    model_id: models.value[0]?.id || 1,
    category_id: categories.value[0]?.id || null,
    rag_kb_id: null,
    is_hot: false,
    enabled: true
  })
  
  Object.assign(paramsForm, {
    temperature: 0.7,
    max_tokens: 2000,
    top_p: 0.9
  })
  
  Object.assign(roleForm, {
    role_name: '',
    role_background: '',
    personality: ''
  })
  
  Object.assign(ragForm, {
    kb_name: '',
    kb_description: '',
    fileList: []
  })
}

const handleAdd = () => {
  resetForms()
  dialogTitle.value = '新增Agent'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description,
    model_id: row.model_id,
    category_id: row.category_id,
    rag_kb_id: row.rag_kb_id || null,
    is_hot: row.is_hot,
    enabled: row.enabled
  })
  
  // 解析 params
  if (row.params) {
    try {
      const params = typeof row.params === 'string' ? JSON.parse(row.params) : row.params
      Object.assign(paramsForm, {
        temperature: params.temperature ?? 0.7,
        max_tokens: params.max_tokens ?? 2000,
        top_p: params.top_p ?? 0.9
      })
    } catch (e) {
      console.error('解析params失败:', e)
    }
  }
  
  // 解析 role
  if (row.role) {
    try {
      const role = typeof row.role === 'string' ? JSON.parse(row.role) : row.role
      Object.assign(roleForm, {
        role_name: role.role_name || '',
        role_background: role.role_background || '',
        personality: role.personality || ''
      })
    } catch (e) {
      console.error('解析role失败:', e)
    }
  }
  
  dialogTitle.value = '编辑Agent'
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    submitting.value = true
    
    // 验证必填字段
    if (!form.category_id) {
      ElMessage.warning('请选择分类')
      return
    }
    
    // 1. 处理 RAG 知识库
    let rag_kb_id = form.rag_kb_id
    
    // 如果填写了新知识库名称且上传了文件，创建新知识库
    if (ragForm.kb_name && ragForm.fileList.length > 0) {
      try {
        const formData = new FormData()
        formData.append('name', ragForm.kb_name)
        if (ragForm.kb_description) {
          formData.append('description', ragForm.kb_description)
        }
        formData.append('embedding_model', 'text-embedding-v3')
        formData.append('vector_store', 'faiss')
        formData.append('chunk_size', '500')
        formData.append('chunk_overlap', '50')
        
        // 添加文件
        ragForm.fileList.forEach(fileItem => {
          formData.append('files', fileItem.raw)
        })
        
        const res = await request.post('/knowledge/knowledge-bases', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        rag_kb_id = res.data.kb_id
        ElMessage.success(`知识库创建成功：${ragForm.kb_name}`)
      } catch (error) {
        console.error('创建知识库失败:', error)
        ElMessage.error('创建知识库失败，但仍会创建 Agent')
      }
    }
    
    // 2. 构建 Agent 数据
    const params = {
      temperature: paramsForm.temperature,
      max_tokens: paramsForm.max_tokens,
      top_p: paramsForm.top_p
    }
    
    const role = {
      role_name: roleForm.role_name,
      role_background: roleForm.role_background,
      personality: roleForm.personality
    }
    
    const data = {
      name: form.name,
      description: form.description,
      model_id: form.model_id,
      category_id: form.category_id,
      rag_kb_id: rag_kb_id,
      is_hot: form.is_hot,
      enabled: form.enabled,
      params: params,
      role: role
    }
    
    // 3. 创建或更新 Agent
    if (form.id) {
      await updateAgent(form.id, data)
      ElMessage.success('更新成功')
    } else {
      await createAgent(data)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error(error)
    ElMessage.error(error.response?.data?.detail || '操作失败')
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 Agent "${row.name}" 吗？删除后将不再显示在列表中。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAgent(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error(error)
    ElMessage.error(error.response?.data?.detail || '删除失败')
  }
}

onMounted(() => {
  loadData()
  loadModels()
  loadCategories()
  loadKnowledgeBases()
})
</script>

<style scoped>
.page-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

